package com.supermarket.ui;

import com.supermarket.dao.UserDAO;
import com.supermarket.model.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 登录界面 - 现代化设计
 * 美观的Swing界面实现
 */
public class LoginFrame extends JFrame {

    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JLabel statusLabel;
    private JCheckBox rememberMeCheckBox;
    private JLabel forgotPasswordLabel;
    private UserDAO userDAO;

    public LoginFrame() {
        userDAO = new UserDAO();
        initializeComponents();
        setupLayout();
        setupEventListeners();
        setFrameProperties();
    }

    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 创建组件
        usernameField = createStyledTextField("请输入用户名");
        passwordField = createStyledPasswordField("请输入密码");
        loginButton = createStyledButton("登录", new Color(40, 167, 69));
        registerButton = createStyledButton("注册", new Color(52, 144, 220));
        statusLabel = new JLabel("", JLabel.CENTER);
        rememberMeCheckBox = new JCheckBox("记住我");
        forgotPasswordLabel = new JLabel("忘记密码？");

        // 设置字体和样式
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 14);
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 14);
        Font smallFont = new Font("微软雅黑", Font.PLAIN, 12);

        usernameField.setFont(labelFont);
        passwordField.setFont(labelFont);
        loginButton.setFont(buttonFont);
        registerButton.setFont(buttonFont);
        statusLabel.setFont(smallFont);
        statusLabel.setForeground(new Color(220, 53, 69));
        rememberMeCheckBox.setFont(smallFont);
        rememberMeCheckBox.setForeground(new Color(73, 80, 87));
        forgotPasswordLabel.setFont(smallFont);
        forgotPasswordLabel.setForeground(new Color(52, 144, 220));
        forgotPasswordLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 设置组件大小
        usernameField.setPreferredSize(new Dimension(280, 40));
        passwordField.setPreferredSize(new Dimension(280, 40));
        loginButton.setPreferredSize(new Dimension(120, 40));
        registerButton.setPreferredSize(new Dimension(120, 40));
    }

    /**
     * 创建样式化文本框
     */
    private JTextField createStyledTextField(String placeholder) {
        JTextField field = new JTextField();
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));
        field.setBackground(Color.WHITE);
        field.setForeground(new Color(73, 80, 87));
        return field;
    }

    /**
     * 创建样式化密码框
     */
    private JPasswordField createStyledPasswordField(String placeholder) {
        JPasswordField field = new JPasswordField();
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));
        field.setBackground(Color.WHITE);
        field.setForeground(new Color(73, 80, 87));
        return field;
    }

    /**
     * 创建样式化按钮
     */
    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setBackground(backgroundColor);
        button.setForeground(Color.BLACK);
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(backgroundColor.darker());
                button.setForeground(Color.BLACK);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(backgroundColor);
                button.setForeground(Color.BLACK);
            }
        });

        return button;
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());
        getContentPane().setBackground(new Color(248, 249, 250));

        // 主面板
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(40, 50, 40, 50)));

        GridBagConstraints gbc = new GridBagConstraints();

        // 标题
        JLabel titleLabel = new JLabel("超市管理系统", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(new Color(52, 144, 220));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 40, 0);
        mainPanel.add(titleLabel, gbc);

        // 副标题
        JLabel subtitleLabel = new JLabel("欢迎登录", JLabel.CENTER);
        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        subtitleLabel.setForeground(new Color(108, 117, 125));
        gbc.gridy = 1;
        gbc.insets = new Insets(0, 0, 30, 0);
        mainPanel.add(subtitleLabel, gbc);

        // 用户名
        JLabel usernameLabel = new JLabel("用户名");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(usernameLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 20, 0);
        mainPanel.add(usernameField, gbc);

        // 密码
        JLabel passwordLabel = new JLabel("密码");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordLabel.setForeground(new Color(73, 80, 87));
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 8, 0);
        mainPanel.add(passwordLabel, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 15, 0);
        mainPanel.add(passwordField, gbc);

        // 记住我和忘记密码
        JPanel optionsPanel = new JPanel(new BorderLayout());
        optionsPanel.setBackground(Color.WHITE);
        optionsPanel.setOpaque(false);
        optionsPanel.add(rememberMeCheckBox, BorderLayout.WEST);
        optionsPanel.add(forgotPasswordLabel, BorderLayout.EAST);

        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 25, 0);
        mainPanel.add(optionsPanel, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setOpaque(false);
        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);

        gbc.gridx = 0;
        gbc.gridy = 7;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(0, 0, 20, 0);
        mainPanel.add(buttonPanel, gbc);

        // 状态标签
        gbc.gridy = 8;
        gbc.insets = new Insets(0, 0, 0, 0);
        mainPanel.add(statusLabel, gbc);

        // 居中显示
        JPanel centerPanel = new JPanel(new GridBagLayout());
        centerPanel.setBackground(new Color(248, 249, 250));
        GridBagConstraints centerGbc = new GridBagConstraints();
        centerGbc.gridx = 0;
        centerGbc.gridy = 0;
        centerPanel.add(mainPanel, centerGbc);

        add(centerPanel, BorderLayout.CENTER);
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 登录按钮点击事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performLogin();
            }
        });

        // 注册按钮点击事件
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openRegisterFrame();
            }
        });

        // 忘记密码点击事件
        forgotPasswordLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                showForgotPasswordDialog();
            }
        });

        // 回车键登录
        usernameField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                passwordField.requestFocus();
            }
        });

        passwordField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performLogin();
            }
        });
    }

    /**
     * 设置窗口属性
     */
    private void setFrameProperties() {
        setTitle("超市管理系统 - 登录");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setSize(450, 600);
        setLocationRelativeTo(null); // 窗口居中

        // 设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception ignored) {
        }
    }

    /**
     * 显示忘记密码对话框
     */
    private void showForgotPasswordDialog() {
        JDialog dialog = new JDialog(this, "忘记密码", true);
        dialog.setSize(400, 250);
        dialog.setLocationRelativeTo(this);
        dialog.getContentPane().setBackground(Color.WHITE);

        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        GridBagConstraints gbc = new GridBagConstraints();

        // 标题
        JLabel titleLabel = new JLabel("重置密码", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(new Color(52, 144, 220));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 20, 0);
        panel.add(titleLabel, gbc);

        // 用户名输入
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 10, 10);
        panel.add(usernameLabel, gbc);

        JTextField usernameField = new JTextField(15);
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 10, 0);
        panel.add(usernameField, gbc);

        // 新密码输入
        JLabel newPasswordLabel = new JLabel("新密码:");
        newPasswordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 10, 10);
        panel.add(newPasswordLabel, gbc);

        JPasswordField newPasswordField = new JPasswordField(15);
        newPasswordField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        newPasswordField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 0, 20, 0);
        panel.add(newPasswordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.setBackground(Color.WHITE);

        JButton resetButton = createStyledButton("重置密码", new Color(40, 167, 69));
        JButton cancelButton = createStyledButton("取消", new Color(108, 117, 125));

        resetButton.addActionListener(event -> {
            String username = usernameField.getText().trim();
            String newPassword = new String(newPasswordField.getPassword());

            if (username.isEmpty() || newPassword.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "请填写完整信息！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                boolean success = userDAO.resetPassword(username, newPassword);
                if (success) {
                    JOptionPane.showMessageDialog(dialog, "密码重置成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(dialog, "用户名不存在或重置失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(dialog, "重置密码失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(event -> dialog.dispose());

        buttonPanel.add(resetButton);
        buttonPanel.add(cancelButton);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(0, 0, 0, 0);
        panel.add(buttonPanel, gbc);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    /**
     * 执行登录
     */
    private void performLogin() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            statusLabel.setText("请输入用户名和密码");
            return;
        }

        // 显示登录中状态
        statusLabel.setText("正在验证...");
        loginButton.setEnabled(false);

        try {
            User user = userDAO.login(username, password);
            if (user != null) {
                statusLabel.setText("登录成功！");
                statusLabel.setForeground(Color.BLUE);

                // 延迟一下再打开主界面
                Timer timer = new Timer(500, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        openMainFrame(user);
                        dispose();
                    }
                });
                timer.setRepeats(false);
                timer.start();

            } else {
                statusLabel.setText("用户名或密码错误");
                statusLabel.setForeground(Color.RED);
            }
        } catch (Exception ex) {
            statusLabel.setText("登录失败：" + ex.getMessage());
            statusLabel.setForeground(Color.RED);
        } finally {
            loginButton.setEnabled(true);
        }
    }

    /**
     * 打开主界面
     */
    private void openMainFrame(User user) {
        try {
            if (user.isAdmin()) {
                // 打开管理员界面
                Class<?> adminClass = Class.forName("com.supermarket.ui.AdminMainFrame");
                JFrame adminFrame = (JFrame) adminClass.getConstructor(User.class).newInstance(user);
                adminFrame.setVisible(true);
            } else if (user.isCashier()) {
                // 打开收银员界面
                Class<?> cashierClass = Class.forName("com.supermarket.ui.CashierMainFrame");
                JFrame cashierFrame = (JFrame) cashierClass.getConstructor(User.class).newInstance(user);
                cashierFrame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(this, "未知的用户角色：" + user.getRoleName(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "打开主界面失败：" + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 打开注册界面
     */
    private void openRegisterFrame() {
        try {
            new RegisterFrame(this).setVisible(true);
            this.setVisible(false); // 隐藏登录界面
        } catch (Exception e) {
            statusLabel.setText("打开注册页面失败：" + e.getMessage());
            statusLabel.setForeground(Color.RED);
        }
    }

    /**
     * 显示登录界面（从注册界面返回时调用）
     */
    public void showLoginFrame() {
        this.setVisible(true);
    }

    /**
     * 主方法
     */
    public static void main(String[] args) {
        // 设置系统外观
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ignored) {
        }

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginFrame().setVisible(true);
            }
        });
    }
}